/**
 * PlantPlot持有若干CropArea
 *
 *
 * 形状编辑器如何与THREE之间进行通信
 * 数据流向是均是单向的，从shapeEditor到THREE
 *
 */

import * as THREE from 'three';
const mockCropArea = [
  {
    x: 0.0225,
    y: 0.06540624618530273,
  },
  {
    x: 0.27875,
    y: 0.07290624618530274,
  },
  {
    x: 0.17625,
    y: 0.9354062461853028,
  },
  {
    x: 0.09,
    y: 0.9329062461853027,
  },
];

function getPlantPlotInfo(mesh) {
  if (!mesh || mesh.name !== 'custom-plant-plot') {
    console.error('不是有效的植物地块网格');
    return null;
  }

  // 获取第一个点（基准点）
  const positionAttribute = mesh.geometry.attributes.position;
  const firstPoint = new THREE.Vector3().fromBufferAttribute(positionAttribute, 0);

  // 应用网格变换（旋转、位置等）
  mesh.updateMatrixWorld();
  const worldFirstPoint = firstPoint.clone().applyMatrix4(mesh.matrixWorld);

  // 计算边界框尺寸（长和宽）
  mesh.geometry.computeBoundingBox();
  const size = new THREE.Vector3();
  mesh.geometry.boundingBox.getSize(size);
  console.log('size', size);
  // 这里应该获取的是x和y轴的长度
  const xLength = size.x;
  const yLength = size.y;

  return {
    basePoint: worldFirstPoint, // 第一个点作为基准点
    xLength,
    yLength,
  };
}

export function convertCropAreaRawData(plantPlot, pointArr = mockCropArea) {
  /**
   *  - 基于plantPlot
   *  - 获取种植区域的基准点坐标 + 长和宽
   *  - 根据rawDatas的便宜百分比计算出用于THREE的坐标
   */
  const { basePoint, xLength, yLength } = getPlantPlotInfo(plantPlot);
  const CropAreaRenderData = [];
  if (Array.isArray(pointArr)) {
    pointArr.forEach((point) => {
      const { x, y } = point;
      const xPoint = basePoint.x + x * xLength;
      // MARK:canvas左上角替换为THREE的左下角
      const yPoint = basePoint.y + (1 - y) * yLength;
      CropAreaRenderData.push([xPoint, yPoint]);
    });
  }
  return CropAreaRenderData;
}

export default class PlantPlot {
  /**
   * TODO: 初始化时
   * 传入Plot的尺寸，插入THREE时需要rotate
   * 传入scene，完成初始化操作
   */

  /**
   * @type {THREE.Scene}
   */
  scene = null;
  /**
   * @type {THREE.Mesh}
   */
  plantPlot = null;
  constructor(plantPlotOption) {
    const { scene, points } = plantPlotOption;
    const mesh = this.createPlantPlot(points);
    this.plantPlot = mesh;
    scene.add(mesh);
  }

  /**
   * TODO: 当前的scene.add在外部,考虑将其移入内部
   * 创建简单多边形Mesh（无孔洞）
   * @param {Array<Array<number>>} points - 多边形轮廓点集，格式为 [[x1, y1], [x2, y2], ...]
   * @param {Object} [options] - 可选配置项
   * @param {THREE.Material} [options.material] - 自定义材质，默认绿色基础材质
   * @param {number} [options.color] - 材质颜色（当未提供自定义材质时有效），默认0x00ff00
   * @param {boolean} [options.doubleSided] - 是否双面渲染，默认false
   * @returns {THREE.Mesh|null} 生成的多边形Mesh对象，失败时返回null
   */
  createPlantPlot(points, options = {}) {
    // 验证输入点集
    if (!Array.isArray(points) || points.length < 3) {
      console.error('多边形至少需要3个点');
      return null;
    }

    // 解构选项参数并设置默认值
    const { material, color = 0xa66a30, doubleSided = true } = options;

    // 创建材质（如果未提供自定义材质）
    const polygonMaterial =
      material ||
      new THREE.MeshBasicMater
    ial({
        color,
        transparent: false,
        side: doubleSided ? THREE.DoubleSide : THREE.FrontSide,
      });

    // 创建Three.js的Shape对象
    const shape = new THREE.Shape();

    // 添加轮廓点
    shape.moveTo(points[0][0], points[0][1]);
    for (let i = 1; i < points.length; i++) {
      shape.lineTo(points[i][0], points[i][1]);
    }
    shape.closePath(); // 确保多边形闭合

    // 创建几何体
    const geometry = new THREE.ShapeGeometry(shape);



    // 创建网格
    const mesh = new THREE.Mesh(geometry, polygonMaterial);
    mesh.rotateX(-Math.PI / 2);

    // 设置名称以便于识别
    mesh.name = 'custom-plant-plot';
    return mesh;
  }

  /**
   * TODO: 暂时通过外部调用，后续移动到CropArea类中
   * 应该将其插入到mesh之下
   */
  createCropArea(points, options = {}) {
    if (!Array.isArray(points) || points.length < 3) {
      console.error('多边形至少需要3个点');
      return null;
    }

    // 解构选项参数并设置默认值
    const { material, color = 0x569230, doubleSided = true, offsetX = 0, offsetY = 0 } = options;

    // 创建材质（如果未提供自定义材质）
    const polygonMaterial =
      material ||
      new THREE.MeshBasicMaterial({
        color,
        transparent: false,
        side: doubleSided ? THREE.DoubleSide : THREE.FrontSide,
      });

    // 创建Three.js的Shape对象
    const shape = new THREE.Shape();

    // 添加轮廓点
    shape.moveTo(points[0][0], points[0][1]);
    for (let i = 1; i < points.length; i++) {
      shape.lineTo(points[i][0], points[i][1]);
    }
    shape.closePath(); // 确保多边形闭合

    // 创建几何体
    const geometry = new THREE.ShapeGeometry(shape);

    // 创建网格
    const mesh = new THREE.Mesh(geometry, polygonMaterial);

    this.plantPlot.add(mesh);
    // Z轴的值需要根据rotate的方向确定
    mesh.position.set(offsetX, offsetY, 0.1);
    return mesh;
  }
}
